package net.neptech.listener.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import net.neptech.model.dto.InstanceParamDto;
import net.neptech.listener.AbstractEventListenerStrategy;
import net.neptech.service.RemoteService;
import net.neptech.util.FlowableUtil;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

import static net.neptech.enums.workflow.InstanceConstant.VariableKey.APPROVE_RESULT;
import static net.neptech.enums.workflow.InstanceConstant.VariableKey.REDIS_KEY_OF_FLOW_UNIQUE_ID;

/**
 * 流程取消了
 */
@Slf4j
@Component
public class ProcessCancelEventListener extends AbstractEventListenerStrategy implements InitializingBean {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private RemoteService remoteService;

    /**
     * 处理数据
     */
    @Override
    public void handle(FlowableEvent event) {
        //流程开完成
        org.flowable.engine.delegate.event.impl.FlowableProcessCancelledEventImpl e = (org.flowable.engine.delegate.event.impl.FlowableProcessCancelledEventImpl) event;
        DelegateExecution execution = e.getExecution();
        String tenantId = execution.getTenantId();
        String processInstanceId = e.getProcessInstanceId();
        String processDefinitionId = e.getProcessDefinitionId();
        String flowId = FlowableUtil.getFlowId(processDefinitionId);
        RuntimeService runtimeService = SpringUtil.getBean(RuntimeService.class);
        Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
        //结果
        Integer finalResult = execution.getVariable(StrUtil.format("{}_{}", flowId, APPROVE_RESULT), Integer.class);
        InstanceParamDto instanceParamDto = new InstanceParamDto();
        instanceParamDto.setProcessInstanceId(processInstanceId);
        instanceParamDto.setCancel(true);
        instanceParamDto.setResult(finalResult);
        instanceParamDto.setFlowId(flowId);
        instanceParamDto.setParamMap(variables);
        remoteService.processEndEvent(instanceParamDto);
        //删除flowuniqueid
        redisTemplate.delete(StrUtil.format(REDIS_KEY_OF_FLOW_UNIQUE_ID,processInstanceId));
        //删除执行人
        redisTemplate.delete(StrUtil.format("resolveAssignee_{}",processInstanceId));
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        afterPropertiesSet(FlowableEngineEventType.PROCESS_CANCELLED.toString());
    }
}
